package com.cn.test;

import com.cn.mapper.UserMapper1;
import com.cn.mapper.UserMapper2;
import com.cn.pojo.User;
import com.cn.utils.SqlSessionUtil;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 3.3 使用小技能
 */
public class UserTest2 {
    /**
     * 3.3.1 获取自增的主键值
     * 在<insert>中设置useGeneratedKeys="true",keyProperty="类中与主键对应的属性名"
     */
    @Test
    public void test1() throws IOException{
        SqlSession sqlSession = SqlSessionUtil.getSqlSession();
        UserMapper2 userMapper2 = sqlSession.getMapper(UserMapper2.class);
        User user = new User(null,"小红","123456","女");
        int count = userMapper2.insertUserGetID1(user);
        if (count>0){
            System.out.println("插入成功");
        }else{
            System.out.println("插入失败");
        }
        System.out.println("数据库生成的主键值为:"+user.getId());
    }

    /**
     * 3.3.1 获取自增的主键值
     * 方式二 使用<selectKey>
     * @throws IOException
     */
    @Test
    public void test2() throws IOException{
        SqlSession sqlSession = SqlSessionUtil.getSqlSession();
        UserMapper2 userMapper2 = sqlSession.getMapper(UserMapper2.class);
        User user = new User(null,"小恬","123456","女");
        int count = userMapper2.insertUserGetID2(user);
        if (count>0){
            System.out.println("插入成功");
        }else{
            System.out.println("插入失败");
        }
        System.out.println("数据库生成的主键值为:"+user.getId());
    }

    /**
     * 3.3.2 传递表名
     */
    @Test
    public void test3() throws IOException{
        SqlSession sqlSession = SqlSessionUtil.getSqlSession();
        UserMapper2 userMapper2 = sqlSession.getMapper(UserMapper2.class);
        int count = userMapper2.getCount("user");
        System.out.println("表中共有"+count+"条数据");
        sqlSession.close();
    }

    /**
     * 3.3.3 批量删除
     */
    @Test
    public void test4() throws IOException{
        SqlSession sqlSession = SqlSessionUtil.getSqlSession();
        UserMapper2 userMapper2 = sqlSession.getMapper(UserMapper2.class);
        int count = userMapper2.deleteUsers("1,6,8");
        if (count>0){
            System.out.println("删除成功");
        }else{
            System.out.println("删除失败");
        }
    }

}
